package com.cherry.androidviewdemo.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.cherry.androidviewdemo.utils.sp2px

/**
 * @author DongMS
 * @since 2020/6/5
 */
class TextIndexBar @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null, defStyle: Int = 0) : View(context, attributeSet, defStyle) {

    private val normalPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val touchPaint = Paint(Paint.ANTI_ALIAS_FLAG)

    private var currentTouchLetter = ""

    private val letters = Array(26) {
        (65 + it).toChar().toString()
    }

    init {

        normalPaint.textSize = 12f.sp2px(context)
        normalPaint.color = Color.BLUE

        touchPaint.textSize = 12f.sp2px(context)
        touchPaint.color = Color.RED
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        val textWidth = letters.map {
            normalPaint.measureText(it)
        }.max()!!
        setMeasuredDimension((textWidth + paddingLeft + paddingRight).toInt(), MeasureSpec.getSize(heightMeasureSpec))
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val size = letters.size
        val halfWidth = width / 2
        val itemHeight = getItemHeight()
        val halfHeight = itemHeight / 2
        for (i in 0 until size) {
            val dx = halfWidth - normalPaint.measureText(letters[i]) / 2f
            val centerY = i * itemHeight + halfHeight + paddingTop
            val fontMetrics = normalPaint.fontMetrics
            val dy = (fontMetrics.bottom - fontMetrics.top) / 2f - fontMetrics.bottom
            val baseline = centerY + dy
            if (currentTouchLetter == letters[i]) {
                canvas.drawText(letters[i], dx, baseline, touchPaint)
            } else {
                canvas.drawText(letters[i], dx, baseline, normalPaint)
            }
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (event.action == MotionEvent.ACTION_DOWN || event.action == MotionEvent.ACTION_MOVE) {
            val dy = event.y
            val itemHeight = getItemHeight()
            var currentPos = (dy / itemHeight).toInt()

            if (currentPos < 0) {
                currentPos = 0
            }
            if (currentPos > letters.size - 1) {
                currentPos = letters.size - 1
            }
            currentTouchLetter = letters[currentPos]
            invalidate()
        }
        return true
    }

    private fun getItemHeight() = (height - paddingTop - paddingBottom) / letters.size


}